<template>
  <PageContainer>
    <view class="container">
      <Header :title="pageTitle" :is-box-shadow="false" />
      <view class="disFlxJS bgf pa-15">
        <view>相册封面</view>
        <view class="disFlxAC" @click="upCoverImg">
          <TImage
            v-if="form.coverUrl"
            :src="form.coverUrl"
            width="100rpx"
            height="fit-content"
            mode="widthFix"
          />
          <view v-else class="tipsColor">默认第一张</view>
          <text class="ant-iconfont icon-right fz-14 ml-5 tipsColor"></text>
        </view>
      </view>
      <view class="disFlxJS bgf pa-15 mt-1">
        <view>相册名称</view>
        <view>
          <input
            v-model="form.name"
            style="text-align: right"
            placeholder-style="color: #AAABAB;"
            placeholder="请输入相册名称"
          />
        </view>
      </view>
      <view class="disFlxJS bgf pa-15 mt-1">
        <view class="_isRequired">相册分组</view>
        <view class="disFlxAC" @click="changeGroup">
          <view v-if="checkedGroup?.id">{{ checkedGroup?.name }}</view>
          <view v-else class="tipsColor">请选择分组</view>
          <text class="ant-iconfont icon-right fz-14 ml-5 tipsColor"></text>
        </view>
      </view>
      <view class="disFlxJS bgf pa-15 mt-1">
        <view>发布日期</view>
        <view class="disFlxAC">
          <uni-datetime-picker type="date" v-model="form.publishTime">
            <text :class="{ tipsColor: !form.publishTime }">
              {{ form.publishTime || '请选择发布日期' }}
            </text>
          </uni-datetime-picker>
          <text class="ant-iconfont icon-right fz-14 ml-5 tipsColor"></text>
        </view>
      </view>
      <view class="disFlxJS bgf pa-15 mt-1">
        <view>
          相册置顶
          <text class="fz-12 pl-10 tipsColor">置顶后将在首页首位展示</text>
        </view>
        <view>
          <FormSwitch v-model="formTop" />
        </view>
      </view>
      <view class="bgf pa-15 mt-1">
        <view class="pb-12">相册描述</view>
        <view>
          <textarea
            v-model="form.desc"
            style="width: 100%; height: 200rpx"
            placeholder="请输入相册描述"
            :maxlength="900"
          />
        </view>
      </view>
      <template v-if="!form.id">
        <view class="bgf pa-15 mt-10">已选照片 （{{ form?.photoDtoList?.length ?? 0 }}）</view>
        <view class="bgf pa-14 mt-1">
          <FormUploadFile
            v-model="formPhotoDtoList"
            :limit="9999"
            mediaType="image"
            @updateResult="updateResult"
          />
        </view>
      </template>

      <TButtonGroup position="fixed">
        <TButton class="gutter-btn" text="确定" type="primary" @click="confirm" />
      </TButtonGroup>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* addPhotos 新建相册 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import { navigateBack, navigateTo, onLoad, redirectTo } from '@/router';
  import { reactive, ref, unref, watch } from 'vue';
  import UniDatetimePicker from '@/components/Form/uni_modules/uni-datetime-picker/uni-datetime-picker.vue';
  import FormSwitch from '@/components/Form/components/FormSwitch.vue';
  import FormUploadFile from '@/components/Form/components/upload/FormUploadFile.vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { useUpload } from '@/hooks/core/useUpload';
  import TImage from '@/components/TImage/index.vue';
  import type { PhotosData } from '@/api/admin/types';
  import { photoAlbumGroupList } from '@/api/photoAlbum';
  import type { PhotoAlbumGroupListResult } from '@/api/photoAlbum/types';
  import { IsTop, FileType } from '@/enums/admin';
  import { formatToDate } from '@/utils/dateUtil';
  import { addPhotoAlbum, photoAlbumDetails, modifyPhotoAlbum } from '@/api/admin/index';
  import { onShow } from '@dcloudio/uni-app';
  import { Toast } from '@/utils';
  import { cloneDeep } from 'lodash-es';
  import type { AddPhotos } from '@/router/types/modules';

  const pageTitle = ref('新建相册');
  let callback: AddPhotos['callback'];

  onLoad<'addPhotos'>((op) => {
    callback = op.callback;
    if (op.id) {
      pageTitle.value = '相册设置';
      getDetails(op.id);
      if (op.openUpCoverImg) {
        upCoverImg();
      }
    }
  });

  const form = reactive<PhotosData>({
    id: undefined,
    name: '',
    desc: '',
    coverUrl: '',
    originalCoverUrl: '',
    belongId: 0, // 默认分组
    publishTime: formatToDate(), // 默认当前时间
    top: IsTop.NO, // 默认不置顶
    photoDtoList: [],
  });
  const formTop = ref(false); // 置顶开关
  const formPhotoDtoList = ref(''); // 照片列表
  const checkedGroup = ref<PhotoAlbumGroupListResult>();
  const updateResult = (result: any) => {
    form.photoDtoList = [];
    result.forEach((v: any, i: number) => {
      if (form.photoDtoList) {
        form.photoDtoList[i] = {
          coverUrl: v.filePath,
          url: v.filePath,
          type: FileType.ISIMAGE,
          name: v.fileName,
          size: v.fileSize,
        };
      }
    });
  };
  // 获取相册详情
  const getDetails = (id: number) => {
    photoAlbumDetails(id).then((res) => {
      form.id = res.id;
      form.name = res.name;
      form.desc = res.desc;
      form.coverUrl = res.coverUrl;
      form.originalCoverUrl = res.originalCoverUrl;
      form.publishTime = res.publishTime;
      form.belongId = res.belongId;
      formTop.value = res.sort ? true : false; // 是否置顶回显转换
      _getGroupObj(); // 分组回显
    });
  };
  const _getGroupObj = () => {
    photoAlbumGroupList().then((_r) => {
      _r.forEach((v) => {
        if (v.id === form.belongId) {
          checkedGroup.value = v;
        }
      });
    });
  };

  onShow(() => {
    customUploadImg();
    const checkedObj = uni.getStorageSync('_CLICK_INFO');
    if (checkedObj && checkedObj.type === 'checkedPhotosGroup') {
      checkedGroup.value = checkedObj;
      uni.removeStorageSync('_CLICK_INFO');
    }
  });

  // 上传相册封面
  const { result, successResult, delResultItem, chooseFile, request } = useUpload({
    count: 1,
    isCrop: true,
    customTriggerUpload: true,
    cropOptions: {
      width: 690,
      height: 552,
      scaleRatio: 10,
    },
  });

  async function customUploadImg() {
    if (result.value.length) {
      uni.showLoading({ title: '上传中...', mask: true });
      const item = result.value[0];
      const res = await request('image', item);
      form.coverUrl = res.imagePathBig as string;
      form.originalCoverUrl = res.imagePathBig as string;
      uni.hideLoading();
    }
  }

  function upCoverImg() {
    // 限制上传一张,如存在则删除后再上传
    result.value.forEach((v, i) => {
      delResultItem(i);
    });
    chooseFile({ mediaType: 'image' });
  }

  // 确认新增相册 || 编辑相册
  const confirm = () => {
    const params = cloneDeep(form);
    params.top = unref(formTop) ? IsTop.YES : IsTop.NO; // 是否置顶
    params.belongId = unref(checkedGroup)?.id ?? 0; // 分组ID
    params.name = form.name || form.publishTime + '创建的相册'; // 相册名称赋默认值

    // 封面图赋值默认值
    if (!params.coverUrl || !params.originalCoverUrl) {
      if (form.photoDtoList && form.photoDtoList.length) {
        params.coverUrl = form.photoDtoList[0].coverUrl;
        params.originalCoverUrl = form.photoDtoList[0].url;
      }
    }

    if (formInspect(params)) {
      if (params.id) {
        modifyPhotoAlbum(params).then(() => {
          navigateBack();
          callback?.();
        });
      } else {
        addPhotoAlbum(params).then((id) => {
          redirectTo({ name: 'addPhotosSuccess', options: { id } });
          callback?.();
        });
      }
    }
  };
  const changeGroup = () => {
    navigateTo({
      name: 'photosGroup',
      options: { isChecked: true, checkedId: unref(checkedGroup)?.id ?? undefined },
    });
  };

  // 表单必填检验
  const formInspect = (form: PhotosData) => {
    if (!form.belongId) {
      Toast('请选择分组');
      return false;
    } else {
      return true;
    }
  };
</script>

<style lang="scss" scoped>
  .container {
    font-size: 28rpx;
    .tipsColor {
      color: #aaabab;
    }
    .bgf {
      background-color: #fff;
    }
    .flexEnd {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      height: 100%;
    }
  }
</style>
